<template>
    <div>
        <el-form class="form-box" ref="formRef" :model="form" label-width="auto" size="large">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="收款金额：" prop="salaAmt">
                        <div class="salaAmt">{{ unpay }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="赠送金额：" prop="payAmt">
                        <el-input v-model="form.payAmt" placeholder="请输入金额" disabled @focus="focusForm('payAmt')"
                            @blur="blurForm" clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="赠送人：" prop="giftUser">
                        <el-select v-model="form.giftUser" filterable @change="handleGiftUserChange">
                            <el-option v-for="item in giftUser_options"  :key="item.code" :value="item.code"
                                :label="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                      <div class="jt-limitMoney" v-if="Object.keys(limitMoeyobj).length > 0">
                            <div>总额度:<span>{{ limitMoeyobj.limitMoney }}</span></div>
                            <div>已经使用的额度:<span>{{ limitMoeyobj.usedMoney }}</span></div>
                            <div>剩余额度：<span>{{ limitMoeyobj.residueMoney }}</span> </div>
                      </div>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="赠送备注：" prop="giftRemark">
                        <el-input v-model="form.giftRemark" placeholder="请输入备注" @focus="focusForm('giftRemark')"
                            @blur="blurForm" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                        <div class="k-continar">
                              <div class="k-item"   :class="{'k-item-Active': selectedIndex === index}"  @click="selectItem(index,item)"  v-for="(item,index) in resmkList " :key="index">
                                {{ item.name }}
                              </div>
                        </div>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup >
import { formatDecimal } from '@/utils/chenhao'
import Api from '@/api'
import useConfigStore from '@/store/config'
import ls from '@/lib/ls'
const configStore = useConfigStore()
// 接收父组件参数 props
const props = defineProps({
    tableInfo: {
        type: Object,
        required: false,
    },
    selectWares: {
        type: Array,
        required: false,
    },
    received: {
        type: String,
        required: false,
    },
    form: {
        type: Object,
        required: false,
    },
    price: {
        type: String,
        required: false,
    },
    unpay: {
        type: String,
        required: false,
    },
    payData: {
        type: Array,
        required: false,
    },
    saleData: {
        type: Array,
        required: false,
    },
    details: {
        type: Array,
        required: false,
    },
})
const tableInfo = toRef(props, 'tableInfo')
const selectWares = toRef(props, 'selectWares')
const received = toRef(props, 'received')
const price = toRef(props, 'price')
const unpay = toRef(props, 'unpay')
const form = toRef(props, 'form')
const payData = toRef(props, 'payData')
const saleData = toRef(props, 'saleData')
const details = toRef(props, 'details')

const emit = defineEmits(['focusForm'])


watch(() => unpay.value, (newvalue, oldvalue) => {
    form.value.payAmt = newvalue
})

// 数字键盘
const focusForm = (str) => {
    // keyboard.value = true
    emit('focusForm', str)
}
const blurForm = (params) => {
    // keyboard.value = false
}

// 获取挂账人列表OPTIONS
let giftUser_options = ref([])
const get_giftUser_options = (params) => {
    Api.Common.PcObjProcess.Do({ "functionName": "GetPerUserList", "orgCode": "0004", "contentData":"" }).then(res => {
        console.log('获取赠送人 res :>> ', res);
         giftUser_options.value =  res.result
    })

}
get_giftUser_options()


const limitMoeyobj = ref({})
const  handleGiftUserChange = (type) =>{
        giftUser_options.value.forEach(item => {
            if (type === item.code)  limitMoeyobj.value = { ...item.posPermission };
        });
  }

// 父组件小键盘点击确定
const handleKeyboardConfirm = async(params) => {
    if (unpay.value <= 0) return ElNotification({
        title: '提示',
        message: '收款金额为0无法收款',
        type: 'warning',
    })
    if (Number(form.value.payAmt) > Number(unpay.value)) return ElNotification({
        title: '提示',
        message: '收取金额不能大于收款金额',
        type: 'warning',
    })
    if (!form.value.payAmt) return ElNotification({
        title: '提示',
        message: '请输入收取金额',
        type: 'warning',
    })
    if (payData.value.length > 0) return ElNotification({
        title: '提示',
        message: '赠送不能组合买单',
        type: 'warning',
    })
    if (saleData.value.length > 0) return ElNotification({
        title: '提示',
        message: '赠送不能使用折扣优惠、抹零、服务费、补抵消等',
        type: 'warning',
    })
    if (!form.value.giftUser) return ElNotification({
        title: '提示',
        message: '赠送人必须选择',
        type: 'warning',
    })
    configStore.payFlag = true // 支付开关
    // 处理勾选的商品
    let detailList = []
    if (details.value.length > 0) {
        detailList = details.value
    } else {
         console.log(selectWares.value);
        let toolArr = []
        selectWares.value.forEach(item=>{
            toolArr.push(item)
            if (item.subGoods && item.subGoods.length > 0) {
                toolArr.push(...item.subGoods)
            }
        })
   
        console.log(toolArr);
        
        detailList = toolArr.map(item => {
            return item.itemCode
        })
    }
    const obj = {
        zffs: form.value.actionType,
        skje: formatDecimal(form.value.payAmt),
        consumeCode: form.value.consumeCode,
        payType: '011',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        giftUser: form.value.giftUser,
        giftRemark: form.value.giftRemark,
        detailList,
    }
    const data = {
        payType: '011',
        consumeCode: tableInfo.value.consumeCode,
        roomCode: tableInfo.value.roomCode,
        payBatchCode: tableInfo.value.payBatchCode,
        orderAmt: price.value,
        realPayAmt: form.value.payAmt,
        detailList: detailList.join(','),
        payList: [obj],
        serviceAmt: saleData.value
    }
    Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "orgCode": "0004", "contentData": data })
        .then(res => {
            configStore.ispaying.id ++
            console.log('买单确认res :>> ', res);
            obj.itemCode = res.itemCode
            obj.payBatchCode = res.payBatchCode
            tableInfo.value.payBatchCode = res.payBatchCode
            payData.value.push(obj)
            form.value.payAmt = ''
            form.value.giftUser = ''
            form.value.giftRemark = ''
            ls.set('payBatchCode', res.payBatchCode)
        })
        .catch(err=>{
            configStore.ispaying.id ++
        })

}

const resmkList = ref([])
const selectedIndex = ref(null);
// 点击事件处理
const selectItem = (index,v) => {
  selectedIndex.value = index; // 更新选中的项索引
  props.form.giftRemark = v.name
};
const get_source_options = () => {
    Api.Common.PcObjProcess.Do({ "functionName": "GetDicData", "orgCode": "0004", "contentData": { parentCode: 606 } }).then(res => {
        console.log('获取字典 res :>> ', res);
        resmkList.value =  res.result
    })
}

get_source_options()

// 暴露方法给父组件
defineExpose({ handleKeyboardConfirm })
</script>

<style scoped lang="scss">
.form-box {
    margin-top: 20px;

    ::v-deep {
        .el-input__wrapper {
            background: #F9F9F9;
            border-radius: 8px;
            border: 0;
            font-size: 16px;
            color: #999999;
        }
    }

    .salaAmt {
        font-weight: 400;
        font-size: 16px;
        color: #FF3333;
    }

}
.k-continar {
    margin-top: 15px;
    position: relative;
    top: -10px;
    display: flex;
    justify-content: space-between;
    .k-item {
        cursor: pointer;
         height: 36px;
         line-height: 36px;
         padding: 0 6px;
         margin-right: 10px;
         background: #e6e6e6;
         border-radius: 6px;
         font-size: 10px;
    }
    .k-item-Active {
        background: #ffd400;
    }
}

.jt-limitMoney {
    display: flex;
    justify-content: space-between;
    // padding-left: 84px;
    margin-bottom: 10px;
    font-size: 13px;
    span {
        color: red;
    }
}
::v-deep .el-form-item {
     margin-bottom: 8px !important;
}
</style>
